package twitmasturbation.servlet;

import java.io.IOException;
import java.util.List;
import java.util.Iterator;
import java.util.HashMap;
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import twitmasturbation.Constants;
import twitmasturbation.jdo.PMF;
import twitmasturbation.jdo.table.HistoryTbl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class IndexServlet extends HttpServlet {

	/** {@link org.apache.commons.logging.Log} オブジェクト。 */
	protected static final Log LOG = LogFactory.getLog(PostServlet.class);

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//LOG.warn("beginning of IndexServlet");
		System.out.println("beginning of IndexServlet");

		int spermSum = 0;
		int[] masturbationCounts = new int[Constants.GRAPH_DAYS]; // 初期値０なんで初期化不要
		String[] spermGraphAxisLabels = new String[Constants.GRAPH_DAYS];
		String beginningDate = "";
		PersistenceManager pmGet = PMF.get().getPersistenceManager();
		try {
	        // 累計何回目のオナニーかをHistoryTblから調べる
	        // FIXME:select出来るのは1000件までなんでオナニー1000回までしかカウント出来ない
	        String query = "select from " + HistoryTbl.class.getName();
	        System.out.println("実行クエリ:" + query);
	        List<HistoryTbl> all_histories = (List<HistoryTbl>) pmGet.newQuery(query).execute();
	        spermSum = Constants.SPERM * all_histories.size();

			// 射精グラフ描画用データ作成
			{
				// 直近 Constants.GRAPH_DAYS 日分の射精データを取得し、日付毎にカウント
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_MONTH, -Constants.GRAPH_DAYS + 1);
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				Date beginning_date = calendar.getTime();
				query = "select from " + HistoryTbl.class.getName();
						//+ " date >= beginning_date"
						//+ " parameters Date beginning_date";
				List<HistoryTbl> recent_histories = null;
				try {
					recent_histories = (List<HistoryTbl>)pmGet.newQuery(query).execute(beginning_date);
				} finally {
				}

				// 射精回数をカウント
				long beginning_date_timestamp = beginning_date.getTime();
				if (recent_histories.iterator().hasNext()) {
					for (HistoryTbl h : recent_histories) {
						Date date = h.getDate();
						// h.getDate()で得られる時間がGMTなので日本時間に合わせて+9:00する
						long timestamp = date.getTime();
						timestamp = timestamp + (1000 * 60 * 60 * 9L);
						int index = (int)(timestamp - beginning_date_timestamp) / 86400000;
						if(index > masturbationCounts.length){
							continue;
						}
						masturbationCounts[index] += 1;
					}
				}
				// 日付のリストを作成（mm/dd）（masturbationCountsと同じ要素数）
				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd");
				Date _date = beginning_date;
				for (int i = 0; i < Constants.GRAPH_DAYS; i++) {
					String _date_str = sdf.format(_date);
					spermGraphAxisLabels[i] = _date_str;
					_date.setTime(_date.getTime() + 86400000);
				}
				// 初日の日付（yyyy/mm/dd）
				sdf = new SimpleDateFormat("yyyy/MM/dd");
				beginningDate = sdf.format(beginning_date);
				System.out.println("beginningDate: " + beginningDate);
			}
		} finally {
			pmGet.close();
		}

		// 描画パラメータセット
        request.getSession().setAttribute("spermConst", Constants.SPERM);
        request.getSession().setAttribute("spermSum", spermSum);
        request.getSession().setAttribute("masturbationCounts", masturbationCounts);
        request.getSession().setAttribute("spermGraphAxisLabels", spermGraphAxisLabels);
        request.getSession().setAttribute("beginningDate", beginningDate);

		// 描画
		response.sendRedirect(request.getContextPath() + "/index.jsp");
		System.out.println("redirecting to: " + request.getContextPath() + "/");
    }

}
